package bgapi

import (
	"bgs/db"
	// sqlc "bgs/db/sqlc"
	// "bgs/util"
	"bytes"
	// "context"
	"encoding/json"
	"fmt"

	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"
)

var (
	lastPeriodicNotificationMessage *PeriodicNotificationMessage = nil
)

// EnumPeriodicNotificationType 周期性通知类型
type EnumPeriodicNotificationType string

const (
	// PeriodicNotificationTypeCloseTimeoutUnpayOrder 关闭超时的未支付订单
	PeriodicNotificationTypeCloseTimeoutUnpayOrder EnumPeriodicNotificationType = "close_timeout_unpay_order"
)

// PeriodicNotificationMessage 周期性通知 message struct
type PeriodicNotificationMessage struct {
	TS   int64 `json:"ts"`
	Data struct {
		Type EnumPeriodicNotificationType `json:"type"`
	} `json:"data"`
}

// PeriodicNotificationHandler 周期性通知 message handler
type PeriodicNotificationHandler struct {
	dao  *db.PgDao
	slog *zap.SugaredLogger
}

// NewPeriodicNotificationHandler create a new handler for 周期性消息
func NewPeriodicNotificationHandler(pgdao *db.PgDao, slog *zap.SugaredLogger) *PeriodicNotificationHandler {
	return &PeriodicNotificationHandler{
		dao:  pgdao,
		slog: slog.With("module", "PeriodicNotificationHandler"),
	}
}

// HandleMessage implements the Handler interface.
func (h *PeriodicNotificationHandler) HandleMessage(m *nsq.Message) error {
	if len(m.Body) == 0 {
		// Returning nil will automatically send a FIN command to NSQ to mark the message as processed.
		return nil
	}

	h.slog.Infof("UserFollowMessage=>%s", string(m.Body))

	v := &PeriodicNotificationMessage{}
	if decodeErr := json.NewDecoder(bytes.NewReader(m.Body)).Decode(v); decodeErr != nil {
		return fmt.Errorf("无法解析信息[PeriodicNotificationMessage]: %v", decodeErr)
	}
	if lastPeriodicNotificationMessage != nil && lastPeriodicNotificationMessage.TS >= v.TS {
		h.slog.Infof("过时的消息: lastPeriodicNotificationMessage.TS:%v,v.TS:%v", lastPeriodicNotificationMessage.TS, v.TS)
		return nil
	}

	h.slog.Infof("type=>%s", v.Data.Type)
	if v.Data.Type == PeriodicNotificationTypeCloseTimeoutUnpayOrder {
		h.slog.Infof("unpayed=>")
	}

	// ctx := context.Background()

	lastPeriodicNotificationMessage = v
	// Returning a non-nil error will automatically send a REQ command to NSQ to re-queue the message.
	return nil
}
